
package com.tenentia.pcmps.swm.data.implementation;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tenentia.pcmps.swm.Constants;
import com.tenentia.pcmps.swm.data.DataAccessException;
import com.tenentia.pcmps.swm.data.beans.ApplicationUser;
import com.tenentia.pcmps.swm.data.beans.UserRole;
import com.tenentia.pcmps.swm.data.interfaces.RolesDAO;
import com.tenentia.pcmps.swm.data.util.IBatisUtilities;

public class RolesDAOImpl implements RolesDAO {

	private static final Logger LOGGER = Logger.getLogger(RolesDAOImpl.class.getPackage().getName());

	RolesDAOImpl() {

		super();
	}

	@Override
	public List<UserRole> getAvailableUserRoles() throws DataAccessException {

		LOGGER.debug(Constants.STRING_L4J_METHOD_BEGIN);

		List<UserRole> methodResult;

		try {
			List<?> tmpList = IBatisUtilities.getSqlMapClient().queryForList("getAvailableRoles");

			if (null == tmpList || tmpList.size() == 0) {
				LOGGER.debug("No results...");
				methodResult = new ArrayList<UserRole>();
			} else {
				methodResult = new ArrayList<UserRole>();
				for (int i = 0; i < tmpList.size(); i++) {
					UserRole tmpInstance = (UserRole) tmpList.get(i);
					methodResult.add(tmpInstance);
					LOGGER.debug("tmpInstance: " + tmpInstance);
				}
			}
		} catch (Exception e) {
			LOGGER.error(e, e);
			throw new DataAccessException(e);
		}

		return methodResult;
	}

	@Override
	public UserRole getUserRole(ApplicationUser user) throws DataAccessException {

		LOGGER.debug(Constants.STRING_L4J_METHOD_BEGIN);

		UserRole methodResult = null;

		try {
			methodResult = (UserRole) IBatisUtilities.getSqlMapClient().queryForObject("getUserRole", user.getInternalID());
		} catch (Exception e) {
			LOGGER.error(e, e);
			throw new DataAccessException(e);
		}

		return methodResult;
	}

	@Override
	public UserRole setUserRole(ApplicationUser user) throws DataAccessException {

		LOGGER.debug(Constants.STRING_L4J_METHOD_BEGIN);

		UserRole methodResult;

		if (null == user.getRole() || null == user.getRole().getInternalID()) {
			methodResult = new UserRole();
			methodResult.setInternalID(Long.valueOf(2));
			user.setRole(methodResult);
		}

		try {
			Object tmpObject = IBatisUtilities.getSqlMapClient().insert("insertUserRoleRelation", user);
			return getUserRole(user);
		} catch (Exception e1) {
			LOGGER.error(e1, e1);
			try {
				Object tmpObject = IBatisUtilities.getSqlMapClient().update("updateUserRoleRelation", user);
				return getUserRole(user);
			} catch (Exception e2) {
				LOGGER.error(e2, e2);
				throw new DataAccessException(e2);
			}
		}
	}

}
